import 'dart:async';
import 'package:agora_rtc_engine/agora_rtc_engine.dart';
import 'package:flutter/material.dart';
import 'package:collection/collection.dart';

import '../../../lib_basemodel/user/user.dart';
import '../../../lib_user/user_manager.dart';
import '../hall/room_main/room_rtc_rtm.dart';

mixin RtcMixin {
  late RtcConfig rtcConfig;

  User? get currUser => UserManager.instance.currentUser;
  late ValueNotifier<Set<int>> speakers;

  // 记录上一次的发言时间，用于筛选出持续低音量的用户（也作为正在发言的用户）
  final Map<int, int> _speakersWithTime = {};

  Timer? _speakerTimer;

  var _isBroadcaster = false;

  Future<void> init() async {}

  Future<void> joinRoom() async {}

  Future<void> leaveChannel() async {}

  Future<void> openMic() async {}

  Future<void> closeMic() async {}

  Future<void> setBroadcaster() async {
    _isBroadcaster = true;
  }

  Future<void> setAudience() async {
    _isBroadcaster = false;
  }

  bool get isBroadcaster => _isBroadcaster;

  Future<void> startPlaySong(String songCode) async {}

  ValueChanged<List<AudioVolumeInfo>> get onVolumeInfo => _onVolumeInfo;

  void _notifyVolume() {
    int now = DateTime.now().millisecondsSinceEpoch;

    // 清除超过1.5秒的speaker
    _speakersWithTime.removeWhere((key, value) => (now - value).abs() >= 1000);

    Set<int> speakerList = _speakersWithTime.keys.toSet();

    if (!const SetEquality<int>().equals(speakerList, speakers.value)) {
      speakers.value = speakerList;
    }
  }

  void _onVolumeInfo(List<AudioVolumeInfo> infoList) {
    int now = DateTime.now().millisecondsSinceEpoch;
    for (var _ in infoList) {
      if ((_.uid ?? -1) < 0 || (_.volume ?? 0) < 4) continue;

      _speakersWithTime[_.uid!] = now;
    }
    _notifyVolume();

    _speakerTimer?.cancel();
    _speakerTimer = Timer(const Duration(milliseconds: 1300), () {
      _notifyVolume();
    });
  }

  MusicContentCenter? get musicCenter => null;

  set musicPlayerId(int id) {}

  Future<void> destroyMediaPlayer(MediaPlayer player) async {}
}
